package com.oj.bfs;

import java.util.LinkedList;
import java.util.Scanner;

public class HelpPrincess {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int row = scanner.nextInt();
            int col = scanner.nextInt();
            int[][] graph = new int[row][col];
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++) {
                    graph[i][j] = scanner.nextInt();
                }
            }
            System.out.println(bfs(new int[]{0, 0}, graph));
        }
    }

    private static final int[][] MOVE = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    public static int bfs(int[] start, int[][] graph) {
        LinkedList<int[]> queue = new LinkedList<>();
        LinkedList<int[]> blockQueue = new LinkedList<>();
        int row = graph.length;
        int col = graph[0].length;
        boolean[][] isVisited = new boolean[row][col];
        isVisited[start[0]][start[1]] = true;
        queue.offer(start);
        int res = 0;
        while (true) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int[] cur = queue.poll();
                if (cur[0] == row - 1 && cur[1] == col - 1) {
                    return res;
                }
                for (int[] move : MOVE) {
                    int nextX = cur[0] + move[0];
                    int nextY = cur[1] + move[1];
                    if (nextX >= 0 && nextX < row && nextY >= 0 && nextY < col
                            && !isVisited[nextX][nextY]) {
                        if (graph[nextX][nextY] == 1) {
                            blockQueue.offer(new int[]{nextX, nextY});
                        } else {
                            queue.offer(new int[]{nextX, nextY});
                        }
                        isVisited[nextX][nextY] = true;
                    }
                }
            }
            if (queue.isEmpty() && !blockQueue.isEmpty()) {
                int bSize = blockQueue.size();
                for (int i = 0; i < bSize; i++) {
                    int[] cur = blockQueue.poll();
                    for (int[] move : MOVE) {
                        int nextX = cur[0] + move[0];
                        int nextY = cur[1] + move[1];
                        if (nextX >= 0 && nextX < row && nextY >= 0 && nextY < col
                                && !isVisited[nextX][nextY]) {
                            if (graph[nextX][nextY] == 1) {
                                blockQueue.offer(new int[]{nextX, nextY});
                            } else {
                                queue.offer(new int[]{nextX, nextY});
                            }
                            isVisited[nextX][nextY] = true;
                        }
                    }
                }
                res++;
            }
        }
    }


}
